import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import {Row,Col,Card,Form,Input,Select,Icon,Button,Dropdown,Menu,InputNumber,DatePicker,Modal,message,Badge,Divider,Upload,Radio,label,Table,Popconfirm ,TimePicker} from 'antd';
import StandardTable from '../../components/StandardTable';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import styles from '../Mana/Role.less';

/*校区管理-课程时间安排*/
const { MonthPicker, RangePicker } = DatePicker;
const FormItem = Form.Item;
const { Option } = Select;
const getValue = obj =>Object.keys(obj).map(key => obj[key]).join(',');


const CreateForm = Form.create()(props => {
  const { modalVisible, form, handleAdd, handleModalVisible,title,obj} = props;
  const {getFieldDecorator} = form;
  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      	fieldsValue.startDate=moment(fieldsValue.startDate).format('HH:mm:ss'); //开始时间
				fieldsValue.endDate=moment(fieldsValue.endDate).format('HH:mm:ss');//结束时间
				if(fieldsValue.dateStatus==undefined){
					fieldsValue.dateStatus=1
				}
				fieldsValue.isDefault=1
				if(fieldsValue.remark==undefined){
					fieldsValue.remark=""
				}
		       form.resetFields();
		       handleAdd(title,obj.syllabusDateId,fieldsValue);
		    });
  };
  return (
    <Modal
      maskClosable={false}
      destroyOnClose={true}
      width={'60%'}
      title={title}
      visible={modalVisible}
      onOk={okHandle}
      onCancel={() => handleModalVisible(false,'','')}
    >
    <Form layout = "horizontal" >
      	<FormItem label="开始时间"labelCol={{span: 10}}  wrapperCol={{span: 10}} className={styles.w50left}>
            {getFieldDecorator('startDate', {
            	initialValue:obj.startDate,
              rules: [{ required: true, message: '课程时间不能为空!' }],
            })(<TimePicker  placeholder="请选择" style={{width:'100%'}} />)}
      	</FormItem>
      	<FormItem label="结束时间" labelCol={{span: 8}}  wrapperCol={{span: 12}} className={styles.w50left}>
            {getFieldDecorator('endDate', {
            	initialValue:obj.endDate,
              	rules: [{ required: true, message: '课程时间不能为空!' }],
            })(<TimePicker  placeholder="请选择" style={{width:'100%'}} />)}
      	</FormItem>
      	<FormItem label="时间状态"  labelCol={{span: 8}}  wrapperCol={{span: 12}} className={styles.w50left}>
            {getFieldDecorator('dateStatus', {
            	initialValue:obj.dateStatus==undefined ? "1":obj.dateStatus,
            })(<Select showSearch    style={{ width: '100%' }} placeholder="请选择">
			    <Option value="1">有效</Option>
			    <Option value="0">无效</Option>
			  </Select>)}
      	</FormItem>
      	<FormItem label="备注" labelCol={{span: 4}}  wrapperCol={{span: 18}}>
            {getFieldDecorator('remark', {
            	initialValue:obj.remark,
            	rules: [{ required: true, message: '备注不能为空!' }],
            })(<Input />)}
      	</FormItem>
    	</Form>
    </Modal>
  );
});

@connect(({ campus, loading ,menu}) => ({
  campus,
  loading: loading.models.campus,
  threeMenu: menu.threeMenu,
}))
@Form.create()
export default class TableList extends PureComponent {
	state = {
	    modalVisible: false,
	    selectedRows: [],
	    formValues: {},
	    obj: "",
	};
    componentDidMount() {
    /*按钮查询*/
		this.props.dispatch({
			type: 'menu/fetch_three_menu',
		});
  	/*默认查询table 数据*/
		this.props.dispatch({	type: 'campus/fetch_classroom'});
  	}

	handleStandardTableChange = (pagination, filtersArg, sorter) => {
	    const { dispatch } = this.props;
	    const { formValues } = this.state;
	    const filters = Object.keys(filtersArg).reduce((obj, key) => {
	    const newObj = { ...obj };
	      newObj[key] = getValue(filtersArg[key]);
	      return newObj;
	    }, {});
	    const params = {
	      currentPage: pagination.current,
	      pageSize: pagination.pageSize,
	      ...formValues,
	      ...filters,
	    };
	    if (sorter.field) {
	      params.sorter = `${sorter.field}_${sorter.order}`;
	    }
	    dispatch({
	      type: 'campus/fetch_course_time',
	      payload: params,
	    });
	};
	handleSelectRows = rows => {
		console.log(rows);
		console.log(rows[0].syllabusDateId);
		this.setState({
			selectedRows: rows,
		});
	};
	/*重置*/
	handleFormReset = () => {
		const {	form,	dispatch} = this.props;
		form.resetFields();
		this.setState({	formValues: {},});
		dispatch({type: 'campus/fetch_course_time',});
	}
	/*查询*/
	handleSearch = e => {
	    e.preventDefault();
	    const { dispatch, form } = this.props;
	    form.validateFields((err, fieldsValue) => {
		    if (err) return;
		    const values = {  ...fieldsValue,};
		    this.setState({ formValues: values,});
		  if(values.startDate==undefined){values.startDate=""}
		  else{values.startDate=moment(values.startDate).format('HH:mm:ss'); }
			if(values.endDate==undefined){values.endDate=""}
			else{values.endDate=moment(values.endDate).format('HH:mm:ss');}
			if(values.dateStatus==undefined){values.dateStatus="1"}
			if(values.isDefault==undefined){values.isDefault="1"}
			if(values.remark==undefined){values.remark=""}
			if(values.upCourseDate==undefined){values.upCourseDate=""}
			
			dispatch({
		        type: 'campus/fetch_course_time',
		        payload:{...values},
	        });
	    });
	};
	/*弹窗*/
  	handleModalVisible = (flag,record,title) => {
  		const { selectedRows } = this.state;
	  	if(flag==false){
	  		this.setState({
		      modalVisible: false,
		    });
	  	}else{
	  		var obj={};
		  	if(title=="新建"){
		  		this.setState({
			      modalVisible: !!flag,
			      title: title,
			      obj: obj,
			    });
	  		}else{
	  			if(record==undefined||Object.keys(selectedRows).length==0){
			    	message.info("还未选择项");
			    }else if(Object.keys(selectedRows).length>1){
			    	message.info("只可选择一项");
			    }else{
			    	obj.startDate=moment(selectedRows[0].startDate,'HH:mm:ss');
			  		obj.endDate=moment(selectedRows[0].endDate,'HH:mm:ss')
			  		obj.syllabusDateId=selectedRows[0].syllabusDateId+=''
			  		obj.dateStatus=selectedRows[0].dateStatus+=''
			  		obj.remark=selectedRows[0].remark
			  		this.setState({
			      modalVisible: !!flag,
			      title: title,
			      obj: obj,
			    });
		    }
				
		  	}
		   
	  	}
  	};
	/*新增,修改*/
	handleAdd = (title,Id,fields) => {
	  	if(title=="新建"){
		    this.props.dispatch({
		      type: 'campus/add_course_time',
		      payload: {...fields,},
		      callback: (res,resMsg) => {
		      	if(res==1){
		      		message.success(resMsg);
		      	}else{
		      		message.error(resMsg);
		      	}
		      },
		    });
	  	}else if(title=="编辑"){
	  		this.props.dispatch({
		      type: 'campus/edit_course_time',
		      payload: {
		      	...fields,
		      	syllabusDateId:Id,
		      },
		      callback: (res,resMsg) => {
		      	if(res==1){
		      		message.success(resMsg);
		      	}else{
		      		message.error(resMsg);
		      	}
		      },
		    });
	  	}
	    this.setState({
	      modalVisible: false,
	    });
	};
  
  	/*删除*/
 	confirmModel=(title,Id)=>{
 		const { dispatch } = this.props;
    	const { selectedRows } = this.state;
	    if(Id==undefined&&Object.keys(selectedRows).length==0){
	    	message.info("还未选择项");
	    }else{
	    	var Ids=[];
		    if(Id!=undefined){
		    	Ids=Id;
		    }else if(selectedRows!=null){
		    	Ids.push(selectedRows.map(row => row.syllabusDateId).join(','));
		    }
		  if(title=="删除"){
		  	Modal.confirm({
			    title: '是否删除当前数据选中',
			    content: '',
			    onOk() {
			      dispatch({
				      type: 'campus/remove_course_time',
				      payload: {syllabusDateIds:Ids,},
				      callback: (res,resMsg) => {
				      	if(res==1){
				      		message.success(resMsg);
				      	}else{
				      		message.error(resMsg);
				      	}
				      },
				  	});
			    },
			});
	  }else{
	    	var state;
	    	if(title=="禁用"){
	    		state=0;
	    	}else{
	    		state=1;
	    	}
	    	Modal.confirm({
					title: '是否'+title+'选中项状态?',
					okText: '确定',
					cancelText: '取消',
					onOk() {
						/*批量修改状态*/
						dispatch({
							type: 'campus/edit_course_time_state',
							payload: {
								syllabusDateIds: Ids,
								state:state,
							},
							callback: (res, resMsg) => {
								if(res == 1) { 
									message.success(resMsg);
								} else { 
									message.error(resMsg);
								}
							},
						});
					}
				});
	  	}
	  }
 	}
	renderSimpleForm() {
	    const { getFieldDecorator } = this.props.form;
	    return (
	      	<Form onSubmit={this.handleSearch} layout="inline">
	      		<Row gutter={{ md: 8, lg: 24, xl: 48 }}>
			        <Col md={8} sm={24}>
			            <FormItem label="开始时间">
			              {getFieldDecorator('startDate')(<TimePicker  placeholder="请选择" style={{width:'100%'}} />)}
			            </FormItem>
			        </Col>
			        <Col md={8} sm={24}>
			            <FormItem label="结束时间">
			              {getFieldDecorator('endDate')(<TimePicker  placeholder="请选择" style={{width:'100%'}} />)}
			            </FormItem>
			        </Col>
			        <Col md={8} sm={24}>
			            <FormItem label="时间状态">
			              {getFieldDecorator('dateStatus')(
			                <Select showSearch    style={{ width: '100%' }} placeholder="请选择">
							    <Option value="1">有效</Option>
							    <Option value="0">无效</Option>
							</Select>
			              )}
			            </FormItem>
			        </Col>
			    </Row>
			    <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
			        <Col md={8} sm={24}>
			            <FormItem label="备注">
			              {getFieldDecorator('remark')(
			                 <Input />
			              )}
			            </FormItem>
			        </Col>
			        <Col md={16} sm={24}>
			            <FormItem>
				            <span style={{ float: 'right', marginBottom: 24 }}>
				            <Button type="primary" htmlType="submit">查询</Button>
				            <Button onClick={this.handleFormReset} style={{ marginLeft: 8 }}>重置</Button>
				           
				            </span>
			            </FormItem>
			        </Col>
			    </Row>
	      </Form>
	    );
	}
	render() {
	    const { campus: { data }, loading ,threeMenu} = this.props;
	    const { selectedRows, modalVisible,title,obj } = this.state;
	    //table 列表
		const columns = [{
			title: '序号',
			dataIndex: 'classroomId',
			key: 'classroomId',
			width: '10%',
			render: (text, record, index) => {
				return index + 1
			}
		}, {
			title: '所属学校',
			dataIndex: 'schoolName',
		}, {
			title: '教室名称',
			dataIndex: 'name',
		}, {
			title: '教师名称',
			dataIndex: 'teacherName',
		}, {
			title: '容纳人数',
			dataIndex: 'acceptanceNum',
		}, {
			title: '临时容纳人数',
			dataIndex: 'tmAcceptanceNum',
		}, {
			title: '状态',
			dataIndex: 'state',
			render: (text, record, index) => {
				if(record.state == 1) {
					return "有效"
				} else if(record.state == 0) {
					return "无效"
				}
			}
		}];
	    const parentMethods = {
	      	handleAdd: this.handleAdd,
	      	handleModalVisible: this.handleModalVisible,
	      	confirmModel:this.confirmModel,
	    };
	    return (
	    	<PageHeaderLayout title="校区系统/课程时间">
	      	<Card bordered={false}>
	          <div className={styles.tableList}>
	            <div className={styles.tableListForm}>{this.renderSimpleForm()}</div>
	            <span> 
	            	{threeMenu.new &&<Button type="primary" onClick={() => this.handleModalVisible(true,'','新建')} style={{ marginLeft: 8 }}>新建</Button>}
	            	{threeMenu.edit &&<Button type="primary" onClick={() => this.handleModalVisible(true,'','编辑')} style={{ marginLeft: 8 }}>编辑</Button>}
	            	{threeMenu.delete &&<Button type="primary" onClick={() => this.confirmModel('删除')} style={{ marginLeft: 8 }}>删除</Button>}
	            	{threeMenu.enable &&<Button type="primary" onClick={() => this.confirmModel('启用')} style={{ marginLeft: 8 }}>启用</Button>}
	            	{threeMenu.enable &&<Button  onClick={() => this.confirmModel('禁用')} style={{ marginLeft: 8 }}>禁用</Button>}
	            </span>
	            <StandardTable
              selectedRows={selectedRows}
              loading={loading}
              data={data}
              columns={columns}
              onSelectRow={this.handleSelectRows}
              onChange={this.handleStandardTableChange}
            />
	          </div>
	        <CreateForm {...parentMethods} modalVisible={modalVisible} title={title} obj={obj}/>
	      </Card>
	    </PageHeaderLayout>
	    );
	}
}
